<?php
/**
 * 兑换码API完整测试脚本
 * 测试所有API端点的功能性和错误处理
 */

// 测试配置
$baseUrl = 'http://www.jiuxin.com';
$testResults = [];

// 辅助函数：发送HTTP请求
function sendRequest($url, $data = [], $method = 'POST') {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return [
        'http_code' => $httpCode,
        'response' => $response,
        'data' => json_decode($response, true)
    ];
}

// 辅助函数：输出测试结果
function outputResult($testName, $result, $expected = null) {
    global $testResults;
    
    $status = '✓ PASS';
    $details = '';
    
    if ($result['http_code'] !== 200) {
        $status = '✗ FAIL';
        $details = "HTTP {$result['http_code']}";
    } elseif ($expected && isset($result['data']['code']) && $result['data']['code'] !== $expected) {
        $status = '✗ FAIL';
        $details = "Expected code {$expected}, got {$result['data']['code']}";
    }
    
    echo sprintf("%-50s %s %s\n", $testName, $status, $details);
    
    if (isset($result['data'])) {
        echo "  Response: " . json_encode($result['data'], JSON_UNESCAPED_UNICODE) . "\n";
    }
    echo "\n";
    
    $testResults[] = [
        'name' => $testName,
        'status' => $status,
        'result' => $result
    ];
}

echo "=== 兑换码API功能测试 ===\n\n";

// 1. 测试验证单个兑换码（无效代码）
echo "1. 测试API端点可访问性\n";
echo str_repeat("-", 50) . "\n";

$result = sendRequest("$baseUrl/index.php/api/RedemptionCode/verify", ['code' => 'INVALID_CODE']);
outputResult("验证无效兑换码", $result);

// 2. 测试批量验证兑换码
$result = sendRequest("$baseUrl/index.php/api/RedemptionCode/batchVerify", ['codes' => 'CODE1,CODE2,CODE3']);
outputResult("批量验证兑换码", $result);

// 3. 测试使用兑换码
$result = sendRequest("$baseUrl/index.php/api/RedemptionCode/use", [
    'code' => 'TEST_CODE',
    'user_id' => 1
]);
outputResult("使用兑换码", $result);

// 4. 测试查询使用历史
$result = sendRequest("$baseUrl/index.php/api/RedemptionCode/history", ['user_id' => 1]);
outputResult("查询使用历史", $result);

// 5. 测试参数验证
echo "\n2. 测试参数验证\n";
echo str_repeat("-", 50) . "\n";

// 测试空参数
$result = sendRequest("$baseUrl/index.php/api/RedemptionCode/verify", []);
outputResult("验证空参数", $result);

$result = sendRequest("$baseUrl/index.php/api/RedemptionCode/use", ['code' => 'TEST']);
outputResult("使用兑换码缺少user_id", $result);

// 6. 测试HTTP方法
echo "\n3. 测试HTTP方法支持\n";
echo str_repeat("-", 50) . "\n";

$result = sendRequest("$baseUrl/index.php/api/RedemptionCode/verify", ['code' => 'TEST'], 'GET');
outputResult("GET方法验证兑换码", $result);

// 7. 创建测试数据并进行实际功能测试
echo "\n4. 创建测试数据进行功能测试\n";
echo str_repeat("-", 50) . "\n";

try {
    // 连接数据库创建测试数据
    require_once __DIR__ . '/config/database.php';
    
    $config = config('database.connections.mysql');
    $dsn = "mysql:host={$config['hostname']};port={$config['hostport']};dbname={$config['database']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password']);
    
    // 创建测试批次
    $stmt = $pdo->prepare("INSERT INTO ba_redemption_code_batch (title, description, total_count, code_length, code_prefix, discount_amount, discount_percent, max_uses_per_code, start_time, end_time, admin_id, status, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    $now = date('Y-m-d H:i:s');
    $endTime = date('Y-m-d H:i:s', strtotime('+1 month'));
    
    $stmt->execute([
        'API测试批次',
        'API功能测试用批次',
        10,
        8,
        'API',
        100.00,
        0.00,
        1,
        $now,
        $endTime,
        1,
        1,
        $now,
        $now
    ]);
    
    $batchId = $pdo->lastInsertId();
    
    // 创建测试兑换码
    $testCode = 'API' . strtoupper(substr(md5(time()), 0, 5));
    $stmt = $pdo->prepare("INSERT INTO ba_redemption_code (code, batch_id, title, description, type, max_uses, used_count, discount_amount, discount_percent, start_time, end_time, status, admin_id, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    $stmt->execute([
        $testCode,
        $batchId,
        'API测试兑换码',
        'API功能测试用兑换码',
        1,
        1,
        0,
        100.00,
        0.00,
        $now,
        $endTime,
        1,
        1,
        $now,
        $now
    ]);
    
    echo "创建测试数据成功：\n";
    echo "  批次ID: $batchId\n";
    echo "  测试兑换码: $testCode\n\n";
    
    // 测试验证有效兑换码
    $result = sendRequest("$baseUrl/index.php/api/RedemptionCode/verify", ['code' => $testCode]);
    outputResult("验证有效兑换码", $result);
    
    // 测试使用有效兑换码
    $result = sendRequest("$baseUrl/index.php/api/RedemptionCode/use", [
        'code' => $testCode,
        'user_id' => 999
    ]);
    outputResult("使用有效兑换码", $result);
    
    // 测试重复使用兑换码
    $result = sendRequest("$baseUrl/index.php/api/RedemptionCode/use", [
        'code' => $testCode,
        'user_id' => 999
    ]);
    outputResult("重复使用兑换码", $result);
    
    // 测试查询使用历史
    $result = sendRequest("$baseUrl/index.php/api/RedemptionCode/history", ['user_id' => 999]);
    outputResult("查询使用历史", $result);
    
    // 清理测试数据
    $pdo->exec("DELETE FROM ba_redemption_code_usage WHERE code = '$testCode'");
    $pdo->exec("DELETE FROM ba_redemption_code WHERE batch_id = $batchId");
    $pdo->exec("DELETE FROM ba_redemption_code_batch WHERE id = $batchId");
    
    echo "测试数据清理完成\n\n";
    
} catch (Exception $e) {
    echo "数据库操作失败: " . $e->getMessage() . "\n";
    echo "跳过实际功能测试\n\n";
}

// 输出测试总结
echo "=== 测试总结 ===\n";
$totalTests = count($testResults);
$passedTests = count(array_filter($testResults, function($test) {
    return strpos($test['status'], 'PASS') !== false;
}));

echo "总测试数: $totalTests\n";
echo "通过测试: $passedTests\n";
echo "失败测试: " . ($totalTests - $passedTests) . "\n";

if ($passedTests === $totalTests) {
    echo "\n🎉 所有测试通过！API功能正常。\n";
} else {
    echo "\n⚠️  部分测试失败，请检查API实现。\n";
}

echo "\n测试完成！\n";
?>